package com.yuanlong.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/discovery")
public class EurekaClientDiscoveryController {

    @Autowired
    private DiscoveryClient client;

    @GetMapping
    public List<Map> discoveryHandler() {
        List<Map> resultList = new ArrayList<Map>();
        Map<String, Object> itemMap;
        List<String> services = client.getServices();
        for (String name : services) {
            List<ServiceInstance> instances = client.getInstances(name);
            for (ServiceInstance instance : instances) {
                itemMap = new HashMap<String, Object>();
                String serviceId = instance.getServiceId();
                itemMap.put("Service Id", serviceId);
                String instanceId = instance.getInstanceId();
                itemMap.put("Instance Id", instanceId);
                String host = instance.getHost();
                itemMap.put("Host", host);
                int port = instance.getPort();
                itemMap.put("Port", port);
                String scheme = instance.getScheme();
                itemMap.put("Scheme", scheme);
                String uri = instance.getUri().toString();
                itemMap.put("URI", uri);
                Map<String, String> metadata = instance.getMetadata();
                itemMap.put("Metadata", metadata);
                resultList.add(itemMap);
            }
        }
        return resultList;
    }
}
